package o.json;

import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collection;

public class JSONParser {
	public Object parseNull(JSONNull json) {
		return null;
	}
	public boolean parseTrue(JSONTrue json) {
		return true;
	}
	public boolean parseFalse(JSONFalse json) {
		return false;
	}
	public String parseString(JSONString json) {
		return json.getValue();
	}
	public Object parseObject(JSONObject json, Class<?> c) {
		try {
			final Object object = c.newInstance();

			for (JSONString key : json.getKeys()) {
				try {
					final JSONValue value = json.getValue(key);
					final Field field = c.getField(key.getValue());
					field.set(object, parse(value, field.getType()));
				} catch(NoSuchFieldException e) {
					e.printStackTrace();
				} catch (IllegalArgumentException e) {
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}

			return object;
		} catch (Exception e) {
		}

		return new Object();
	}
//	public Object[] parseArray(JSONArray json, Class<?> c) throws JSONException {
//		final int length = json.getLength();
//		final Object objects = Array.newInstance(c, length);
//		for (int i = 0; i < length; ++i) {
//			final JSONValue value = json.getValue(i);
//			Array.set(objects, i, parse(value));
//		}
//		return (Object[]) objects;
//	}
	public Collection<?> parseArray(JSONArray json, Class<?> c) throws JSONException {
		final int length = json.getLength();
		final Collection<?> objects = new ArrayList<Object>();
		for (int i = 0; i < length; ++i) {
			final JSONValue value = json.getValue(i);
			Array.set(objects, i, parse(value));
		}
		return objects;
	}
	public Number parseNumber(JSONNumber json) {
		return json.getValue();
	}
	public Object parse(JSONValue value) throws JSONException {
		if (value.isNull())   return parseNull(value.getNull());
		if (value.isTrue())   return parseTrue(value.getTrue());
		if (value.isFalse())  return parseFalse(value.getFalse());

		if (value.isString()) return parseString(value.getString());
		if (value.isNumber()) return parseNumber(value.getNumber());

		throw new JSONException("JSON object is unknown");
	}

	public Object parse(JSONValue value, Class<?> c) throws JSONException {
		if (value.isObject()) return parseObject(value.getObject(), c);
		if (value.isArray())  return parseArray(value.getArray(), c);

		return parse(value);
	}
}
